package com.lance.answer.question_export;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lance.answer.dto.Item;
import com.lance.answer.dto.QuestionAnswer;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>处理获取后的国开答案<p>
 * <p>
 * 获取了大量的题目
 * 主要支持多选和单选等客观题
 * 填空题没有标准答案，格式也比较乱
 * 简单题部分有答案
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/18 9:22
 */
public class GkAnswerFixtmp {

    public static void main(String[] args) throws Exception {
//        String answer = "正确答案是：以血浆HCO3－浓度原发性升高和pH上升为特征的酸碱平衡紊乱。 → 代谢性碱中毒," +
//                " 体内CO2排出障碍或吸入过多引起的以血浆H2CO3浓度原发性增高和pH下降为特征的酸碱平衡紊乱。 → 呼吸性酸中毒, " +
//                "以血浆 HCO3－ 浓度原发性减少而导致pH下降为特征的酸碱平衡紊乱。 → 代谢性酸中毒, " +
//                "以血浆H2CO3浓度原发性减少和pH升高为特征的酸碱平衡紊乱。 → 呼吸性碱中毒";
//
//        boolean hasE = true;
//        while (hasE){
//
//            System.out.println("answer："+answer);
//            String s= answer.substring(answer.indexOf(" →")+2);
//           // System.err.println("s:"+s);
//            if(s.contains(", ")){
//                s = s.substring(0,s.indexOf(", "));
//            }else {
//                hasE = false;
//            }
//            //    String s= answer.substring(13,16);
//            s = Util.dealContent(s);
//            System.out.println("s:"+s);
//            answer = answer.substring(answer.indexOf(", ")+1);
//        }
//        Thread.sleep(2000000);


//        String answerStr = IOUtils.toString(new FileInputStream("D:\\newAnswerTmp\\人文英语1-answer.json"), "utf-8");
//        answerStr = answerStr.replace("\\C", "");
//
//        List<QuestionAnswer> list = JSONObject.parseArray(answerStr, QuestionAnswer.class);
//        System.out.println(list.size());
//        int i = 0;
//        List<QuestionAnswer> deal = Lists.newArrayList();
//
//        StringBuilder sb = new StringBuilder();
//        for (QuestionAnswer answerObject : list) {
//            QuestionAnswer copy = new QuestionAnswer();
//            copy.setAnswers(answerObject.getAnswers());
//            copy.setQuestionTitle(answerObject.getQuestionTitle());
//            deal.add(copy);
//
//            sb.append(answerObject.getQuestionTitle());
//            sb.append("   正确答案："+ JSON.toJSONString(answerObject.getAnswers()));
//            sb.append("\n");
//        }
//
//        FileUtils.write(new File("D:\\newAnswerTmp\\人文英语1.txt"), sb.toString(), "utf-8");
//
//        try {
//            Thread.sleep(20000000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }


        // fix("管理学基础");
        for (File file : new File("d://newAnswerTmp").listFiles()) {
            if (file.isDirectory()) {
                continue;
            }
            try {
                // fixme 有限看deal目录的
                fix(file, "d://newAnswerTmp");
            } catch (Exception e) {
                System.out.println("error:" + file.getName());
                e.printStackTrace();
            }
        }
        // fix(file);
        //System.out.println(MD5Utils.encode("药物化学"+ "上皮组织的特点，不包括（　）。") );
    }


    public static void fix(File file, String destDirect) throws IOException {

        String fileName = file.getName();
        String subjectName = fileName.substring(0, fileName.lastIndexOf(".")).trim();

        String answerStr = IOUtils.toString(new FileInputStream(file), "utf-8");
        answerStr = answerStr.replace("\\C", "");

        List<QuestionAnswer> list = JSONObject.parseArray(answerStr, QuestionAnswer.class);
        System.out.println(list.size());
        int i = 0;
        for (QuestionAnswer answerObject : list) {
            String questionTitle = Util.dealContent(answerObject.getQuestionTitle());
            String questionCodeSrc = answerObject.getQuestionCode();
            String questionCode = MD5Utils.encode(subjectName + questionTitle);
            if (!Objects.equals(questionCodeSrc, questionCode)) {
                System.out.println(questionCodeSrc + " ---> " + questionCode);
            }
            answerObject.setQuestionCode(questionCode);
            if (StringUtils.isEmpty(answerObject.getAnswerType())) {
                answerObject.setAnswerType("click");
            }
            List<String> realAnswers = new ArrayList<>();

            // 完形填空
            if(answerObject.getQuestionType()==6){
                if(null == answerObject.getAnswers()){
                    System.err.println(">>>>>>>>>>>>>:"+answerObject.getQuestionTitle());
                    continue;
                }
                // FIXME 可以程序替换
                //	所以该句内容错误 所以该句内容正确 因此答案为 正确答案为 正确答案是 所以本题选 故选择T 故选 所以这道题选择
                //	所以答案是F 所以答案是T
                for(String answer:answerObject.getAnswers()){
                    if(Strings.isNullOrEmpty(answer)||!answer.contains("所以答案是")){
                        continue;
                    }
                    // 所以答案选
                    String[] array = answer.split("所以答案是");
                    for(int k=1;k<array.length;k++){
                        String s= array[k];
                        s= s.replaceAll("\n","");
                        realAnswers.add(s.substring(0,1));
                    }
                    answerObject.setAnswers(realAnswers);
                }
                continue;
            }

            if(answerObject.getQuestionType()==10){
                if(null == answerObject.getAnswers()){
                    System.err.println(">>>>>>>>>>>>>:"+answerObject.getQuestionTitle());
                    continue;
                }
                // FIXME 可以程序替换
                //	所以该句内容错误 所以该句内容正确 因此答案为 正确答案为 正确答案是 所以本题选 故选择T 故选 所以这道题选择
                //	所以答案是F 所以答案是T
                for(String answer:answerObject.getAnswers()){



                    if(Strings.isNullOrEmpty(answer)){
                        continue;
                    }
                    Item item = new Item();
                    item.setContent(answer);
                    answerObject.setItems(Lists.newArrayList(item));
                    // 所以答案选
                    while (answer.contains("[")&&answer.contains("]")){

                        System.out.println("answer："+answer);
                        String s= answer.substring(answer.indexOf("[")+1,answer.indexOf("]"));
                    //    String s= answer.substring(13,16);
                        s = Util.dealContent(s);
                        System.out.println("s:"+s);
                        realAnswers.add(s);
                        answer = answer.substring(answer.indexOf("]")+1,answer.length());
                    }
                    answerObject.setAnswers(realAnswers);

                }
                continue;
            }


            if(answerObject.getQuestionType()==61){
                if(null == answerObject.getAnswers()){
                    System.err.println(">>>>>>>>>>>>>:"+answerObject.getQuestionTitle());
                    continue;
                }
                // FIXME 可以程序替换
                //	所以该句内容错误 所以该句内容正确 因此答案为 正确答案为 正确答案是 所以本题选 故选择T 故选 所以这道题选择
                //	所以答案是F 所以答案是T
                for(String answer:answerObject.getAnswers()){



                    if(Strings.isNullOrEmpty(answer)){
                        continue;
                    }
                    // 所以答案选

//                    while (answer.contains("[")&&answer.contains("]")){
//
//                        System.out.println("answer："+answer);
//                        String s= answer.substring(answer.indexOf("[")+1,answer.indexOf("]"));
//                        //    String s= answer.substring(13,16);
//                        s = Util.dealContent(s);
//                        System.out.println("s:"+s);
//                        realAnswers.add(s);
//                        answer = answer.substring(answer.indexOf("]")+1,answer.length());
//                    }
                    boolean hasE = true;
                    while (hasE){

                        System.out.println("answer："+answer);
                        String s= answer.substring(answer.indexOf(" →")+2);
                        // System.err.println("s:"+s);
                        if(s.contains(", ")){
                            s = s.substring(0,s.indexOf(", "));
                        }else {
                            hasE = false;
                        }
                        //    String s= answer.substring(13,16);
                        s = Util.dealContent(s);
                        realAnswers.add(s);
                        System.out.println("s:"+s);
                        answer = answer.substring(answer.indexOf(", ")+1);
                    }

                    answerObject.setAnswers(realAnswers);

                }
                continue;
            }



            if (answerObject.getQuestionType() == 4) {
                  System.err.println(subjectName);

                // 填空题的答案在questionTitle里面
                // 筛选回答正确的答题
                if (!questionTitle.contains("结束的试答 正确")) {
                    continue;
                }
                // \n回答 \n评论
                if (!questionTitle.contains("。\n回答") && !questionTitle.contains("。\n评论")) {
                    System.err.println(questionTitle);
                }
                int index;
                if (questionTitle.contains("。\n回答")) {
                    index = questionTitle.indexOf("。\n回答");
                } else {
                    index = questionTitle.indexOf("。\n评论");
                }
                String realTitleName = questionTitle.substring(0, index + 1);
                String answers = questionTitle.substring(index + 1);

                int problemIndex = 1;
                List<String> realAnswerList = Lists.newLinkedList();
                while (answers.contains("子问题 "+problemIndex)){
                    int i1 = answers.indexOf("子问题 "+problemIndex);
                    String si2 = "子问题 "+(problemIndex+1);
                    String si3 = " 答案已保存";
                  if(answers.contains(si2)){
                      realAnswerList.add(answers.substring(i1+6,answers.indexOf(si2)-2));
                      problemIndex++;
                      continue;
                  }
                  if(answers.contains(si3)){
                      realAnswerList.add(answers.substring(i1+6,answers.indexOf(si3)));
                  }
                    problemIndex++;
                }

                answerObject.setAnswers(realAnswerList);
                answerObject.setQuestionTitle(realTitleName);
                continue;
            }

            if (null != answerObject.getAnswers()) {
                for (String item : answerObject.getAnswers()) {
                    if (item.endsWith(" ")) {
                        i++;
                    }
                    if (item.contains("正确答案是：")) {
                        item = item.replace("正确答案是：", "");
                    }
                    if (item.contains("正确答案是：")) {
                        item = item.replace("正确答案是：", "");
                    }
                    if (item.contains("所以答案是：")) {
                        item = item.replace("所以答案是：", "");
                    }
                    // 是判断题
                    if (answerObject.getQuestionType() == 3) {
                        if (item.contains("错")) {
                            item = "错";
                        }
                        if (item.contains("对")) {
                            item = "对";
                        }
                    }
                    // 多选题
                    if (answerObject.getQuestionType() == 2) {
                        //  System.err.println(item);
                        if (item.contains(",")) {
                            for (String s : item.split(",")) {
                                realAnswers.add(Util.dealContent(s));
                            }
                            continue;
                        }
                    }
                    realAnswers.add(Util.dealContent(item));
                }

            }
//            else {
//                System.err.println(subjectName+answerObject.getQuestionTitle());
//            }
            answerObject.setAnswers(realAnswers);
        }

        System.out.println(i);
        String path = destDirect + "/" + subjectName + "-answer.json";
        // 如果答案不存在，就重写 FIXME .............
       if(!new File(path).exists()){
        //   FileUtils.write(new File(path), JSONObject.toJSONString(list, SerializerFeature.PrettyFormat), "utf-8");
        // 这样子会过滤掉没有答案的
           List<QuestionAnswer> newList = Lists.newArrayList();
           for(QuestionAnswer questionAnswer:list){
//               if(questionAnswer.getAnswers()==null){
//                   continue;
//               }
//               if(questionAnswer.getAnswers().size()<1){
//                   continue;
//               }
//              //  过滤掉不完成的答案
//               if(questionAnswer.getQuestionType() == 61&&questionAnswer.getItems().size()!=questionAnswer.getAnswers().size()){
//                   continue;
//               }
               newList.add(questionAnswer);
           }
           FileUtils.write(new File(path), JSONObject.toJSONString(newList, SerializerFeature.PrettyFormat), "utf-8");
       }
    }


}
